import frpOption from "../option.json" with { type: "json" }
import logger from "./logger.js"

import { getStorageKey, localStorage, StorageKeyType } from "./localStorage.js"

import approveNumberList from '../asset/approveNumber.json'     with { type: "json" }

async function syncKingdeeOrder(orderCode, productionOrderList) {
    const storageKey = getStorageKey(orderCode, StorageKeyType.syncKingdeeOrder)
    let syncKingdeeOrderStatus = JSON.parse(localStorage.getItem(storageKey))
    if (syncKingdeeOrderStatus == null) {
        syncKingdeeOrderStatus = []
    }

    const runProductionList = productionOrderList.filter(item => !syncKingdeeOrderStatus.includes(item.code))

    const errMsgList = []
    for (const productionOrder of runProductionList) {
        const approveNumber = approveNumberList.find(item => item['批号'] === productionOrder.oldCode)
        const syncRes = await fetch(`${frpOption.api.syncKingdeeOrder}`, {
            method: "post",
            body: JSON.stringify({
                productionOrderId: productionOrder['数据ID'],
                fz_id: approveNumber['缝制车间'],
                startTimeStr: `${productionOrder.planStartDate} 00:00:00`,
                endTimeStr: `${productionOrder.planEndDate} 00:00:00`
            }),
        }).then((res) => res.json())
        if (syncRes?.code !== 200) {
            errMsgList.push(productionOrder.code + " 金蝶同步失败：" + JSON.stringify(syncRes))
        } else {
            syncKingdeeOrderStatus.push(productionOrder.code)
            logger.info(`${productionOrder.code} 金蝶同步成功`)
        }
    }

    localStorage.setItem(storageKey, JSON.stringify(syncKingdeeOrderStatus))

    if (errMsgList.length > 0) {
        throw new Error('\n' + errMsgList.join("\n"))
    }
}

export { syncKingdeeOrder }